package cn.szv5.leetcode;

/**
 * Leetcode<p>
 * 两数相加<p>
 * Copyright: Copyright (C) 2022 , Inc. All rights reserved. <p>
 * Company: 阿飞工作室<p>
 *
 * @author Carl
 * @since 2022/3/20 12:51
 */
public class AddTwoNumbers2 {

    public static void main(String[] args) {
        Solution solution = new AddTwoNumbers2().new Solution();

        int[] arr1 = {2, 4, 3};
        int[] arr2 = {5, 6, 4};

        ListNode l1 = new AddTwoNumbers2().new ListNode();
        ListNode l2 = new AddTwoNumbers2().new ListNode();

        ListNode l1Cur = l1;
        ListNode l2Cur = l2;

        for (int i = 0; i < arr1.length; i++) {
            ListNode node1 = new AddTwoNumbers2().new ListNode(arr1[i]);
            ListNode node2 = new AddTwoNumbers2().new ListNode(arr2[i]);

            l1Cur.next = node1;
            l1Cur = node1;
            l2Cur.next = node2;
            l2Cur = node2;
        }

        ListNode result = solution.addTwoNumbers(l1.next, l2.next);
        while (result != null) {
            System.out.print(result.val + " ");
            result = result.next;
        }
    }

    class ListNode {
        int val;
        ListNode next;

        ListNode() {

        }

        public ListNode(int val) {
            this.val = val;
        }
    }

    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode p = l1, q = l2;
            ListNode resultHead = new ListNode(-1);
            ListNode curr = resultHead;

            int carry = 0; // 进位
            int num = 0; //当前位数值

            // 1.遍历两个链表
            while (p != null || q != null) { // 以长链表为准
                // 获取当前节点的值：链表较短，已无节点，取0
                int x = p != null ? p.val : 0;
                int y = q != null ? q.val : 0;

                // 2.对应位置的节点数值相加
                int sum = x + y + carry;
                carry = sum / 10;
                num = sum % 10;

                // 3.将计算结果插入新链表尾部
                curr.next = new ListNode(num); //创建新节点
                curr = curr.next;

                p = p == null ? p : p.next;
                q = q == null ? q : q.next;
            }
            if (carry > 0) { //处理进位节点
                curr.next = new ListNode(carry);
            }
            return resultHead.next;
        }
    }
}
